package com.ssyu.examination.questionbank.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ssyu.examination.conmmon.Constants;
import com.ssyu.examination.conmmon.PageModel;
import com.ssyu.examination.conmmon.util.DBUtil;
import com.ssyu.examination.questionbank.entity.QesExamPaperEntity;
import com.ssyu.examination.questionbank.entity.QuestionQesEntity;

public class QesExamPaperService {

	public PageModel<QesExamPaperEntity> listpaper(int page, int rows, String paperName, int courseId, int state) {
		List<Object> paramList = new ArrayList<Object>();
		StringBuilder sb = new StringBuilder(
				"SELECT q.id, q.name,c.text as course__text,q.total_point,q.pass_point,q.total_minutes,q.state FROM qes_exam_paper q,sys_course c ");
		sb.append("WHERE q.course_id=c.id ");
		sb.append("AND q.state=? ");
		paramList.add(state);
		if (courseId != 0) {
			sb.append("AND q.course_id=? ");
			paramList.add(courseId);
		}
		if (StringUtils.isNotBlank(paperName)) {
			sb.append("AND q.name=? ");
			paramList.add(paperName);
		}
		sb.append("ORDER BY q.id DESC LIMIT ?,?");
		paramList.add((page - 1) * rows);
		paramList.add(rows);
		return DBUtil.executeQueryByPage(QesExamPaperEntity.class, sb.toString(), paramList);
	}

	/**
	 * 根据ID获取试卷详情
	 * 
	 * @param id
	 * @return
	 */
	public QesExamPaperEntity getPaper(int id) {
		String sql = "SELECT q.*,c.text as course__text,u.`name` as user__name FROM qes_exam_paper q,sys_course c,sys_user u WHERE q.course_id=c.id AND q.opreate_user_id=u.id AND q.id=?";
		return DBUtil.getUniqueResult(QesExamPaperEntity.class, sql, id);
	}

	/**
	 * 修改试卷状态
	 * 
	 * @param id
	 * @param state
	 * @param operateId
	 * @return
	 */
	public int updateClazzState(int id, int state, int operateId) {
		String sql = "UPDATE qes_exam_paper SET state=?,opreate_user_id=? WHERE id=?";
		return DBUtil.executeUpdate(sql, state, operateId, id);
	}

	/**
	 * 新增试卷
	 * 
	 * @param paramList
	 * @return
	 */
	public long addpaper(List<Object> paramList) {
		long rows = 0;
		Connection connection = DBUtil.getConnection();
		String sql = "INSERT INTO qes_exam_paper VALUES(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),1,null)";
		PreparedStatement prepareStatement = null;
		try {
			prepareStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			DBUtil.setParameter(paramList, prepareStatement);
			prepareStatement.executeUpdate();
			ResultSet generatedKeys = prepareStatement.getGeneratedKeys();
			if (generatedKeys.next()) {
				rows = generatedKeys.getLong(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(prepareStatement, connection);
		}
		return rows;
	}

	/**
	 * 生成单选题
	 * 
	 * @param paramList
	 * @return
	 * @return
	 */

	public List<QuestionQesEntity> singleList(int course, int singleDifficulty, int singleNumber) {
		String singleSql = "SELECT * FROM qes_qestions where course_id=? and question_type=1 and difficulty=? GROUP BY RAND() LIMIT "
				+ singleNumber;
		return DBUtil.executeQuery(QuestionQesEntity.class, singleSql, course, singleDifficulty);
	}

	public List<QuestionQesEntity> singleList(int course) {
		String singleSql = "SELECT * FROM qes_qestions where course_id=? and question_type=1 GROUP BY RAND() LIMIT 10";
		return DBUtil.executeQuery(QuestionQesEntity.class, singleSql, course);
	}

	/**
	 * 生成多选题
	 * 
	 * @param paramList
	 * @return
	 */

	public List<QuestionQesEntity> miltipleList(int course, int multiDifficulty, int multiNumber) {
		String multiSql = "SELECT * FROM qes_qestions where course_id=? and question_type=2 and difficulty=? GROUP BY RAND() LIMIT "
				+ multiNumber;
		return DBUtil.executeQuery(QuestionQesEntity.class, multiSql, course, multiDifficulty);
	}

	public List<QuestionQesEntity> miltipleList(int course) {
		String multiSql = "SELECT * FROM qes_qestions where course_id=? and question_type=2 GROUP BY RAND() LIMIT 10";
		return DBUtil.executeQuery(QuestionQesEntity.class, multiSql, course);
	}

	/**
	 * 生成判断题
	 * 
	 * @param paramList
	 * @return
	 */
	public List<QuestionQesEntity> judgeList(int course, int judgeDifficulty, int judgeNumber) {
		String judgeSql = "SELECT * FROM qes_qestions where course_id=? and question_type=3 and difficulty=? GROUP BY RAND() LIMIT "
				+ judgeNumber;
		return DBUtil.executeQuery(QuestionQesEntity.class, judgeSql, course, judgeDifficulty);
	}

	public List<QuestionQesEntity> judgeList(int course) {
		String judgeSql = "SELECT * FROM qes_qestions where course_id=? and question_type=3 GROUP BY RAND() LIMIT 10";
		return DBUtil.executeQuery(QuestionQesEntity.class, judgeSql, course);
	}

	/**
	 * 创建文件
	 * 
	 * @param fast
	 * @param fileName
	 * @throws IOException
	 */
	public void addPaperFile(String fast, String fileName) throws IOException {
		File file = new File("E:/examination");
		if (file.exists() == false) {
			file.mkdirs();
		}
		File file2 = new File("E:/examination/" + fileName);
		if (file2.exists() == false) {
			file2.createNewFile();
		}
		OutputStream outputStream = new FileOutputStream(file2, true);
		outputStream.write(fast.getBytes());

		outputStream.close();
	}

	public void rebuildPaperFile(String fast, String fileName, String oldUrl) throws IOException {
		File file = new File("E:/examination");
		if (file.exists() == false) {
			file.mkdirs();
		}
		File file1 = new File(oldUrl);
		if (file1.exists()) {
			file1.delete();
		}
		File file2 = new File("E:/examination/" + fileName);
		if (file2.exists() == false) {
			file2.createNewFile();
		}
		OutputStream outputStream = new FileOutputStream(file2, true);
		outputStream.write(fast.getBytes());

		outputStream.close();
	}

	/**
	 * 自动生成试卷
	 * 
	 * @param paramList
	 * @return
	 */
	public long accordAddPaper(List<Object> paramList) {
		long rows = 0;
		Connection connection = DBUtil.getConnection();
		String sql = "INSERT INTO qes_exam_paper VALUES(null,?,?,?,?,100,60,90,10,2,null,10,4,null,20,2,null,?,NOW(),1,null)";
		PreparedStatement prepareStatement = null;
		try {
			prepareStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			DBUtil.setParameter(paramList, prepareStatement);
			prepareStatement.executeUpdate();
			ResultSet generatedKeys = prepareStatement.getGeneratedKeys();
			if (generatedKeys.next()) {
				rows = generatedKeys.getLong(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(prepareStatement, connection);
		}
		return rows;
	}

	/**
	 * 修改地址
	 * 
	 * @param url
	 * @param id
	 * @return
	 */
	public int updateUrl(String url, int id) {
		String sql = "UPDATE qes_exam_paper SET paper_url=?,opreate_time=now() WHERE id=?";
		return DBUtil.executeUpdate(sql, url, id);
	}

	public QesExamPaperEntity previewPaper(int id) {
		String sql = "SELECT paper_url FROM qes_exam_paper WHERE id=?";
		return DBUtil.getUniqueResult(QesExamPaperEntity.class, sql, id);
	}

	public String accordJsonString(QesExamPaperEntity qesExamPaperEntity) {
		String URL = qesExamPaperEntity.getPaperUrl();
		try {
			File file = new File(URL);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), Constants.ENCODE_UTF8);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				StringBuilder str = new StringBuilder();
				while ((lineTxt = bufferedReader.readLine()) != null) {
					str.append(lineTxt);
				}
				read.close();
				return str.toString();
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 分数验证
	 * 
	 * @param totalPoint
	 * @param singleNumber
	 * @param singlePoint
	 * @param multiNumber
	 * @param multiPoint
	 * @param judgeNumber
	 * @param judgePoint
	 * @return
	 */
	public boolean checkPoint(int totalPoint, int singleNumber, int singlePoint, int multiNumber, int multiPoint,
			int judgeNumber, int judgePoint) {
		if (totalPoint != (singleNumber * singlePoint) + (multiNumber * multiPoint) + (judgeNumber * judgePoint)) {
			return false;
		} else {
			return true;
		}

	}

}
